import React, { useEffect, useState } from "react";
import {
    Alert,
    Modal,
    StyleSheet,
    Text,
    TouchableHighlight,
    View,
    Image,
    SectionList,
    TouchableOpacity
} from "react-native";

const Item = ({ item, handleCheck, typeId, checked }) => {
    return (
        <View style={styles.itemContainer}>
            <TouchableOpacity style={styles.itemLeft} onPress={() => handleCheck(item.id, typeId, item.price)}>
                <Image style={styles.checkIcon} source={checked ? require('../assets/checked.png') : require('../assets/check.png')} />
                <Text style={styles.itemName}>{item.name}</Text>
            </TouchableOpacity>
            {item.price === 0 ? <></> : <Text>+${item.price}</Text>}
        </View>
    )
}

const SkuType = ({ name, max, count }) => {
    return (
        <View style={styles.headerContainer}>
            <Text style={styles.headerText}>{name}</Text>
    {max === 0 ? <></> : <Text style={styles.headerLimit}>最多选{max}份{count === 0 ? <></> : <Text>，已选{count}份</Text>}</Text>}
        </View>
    )
}

const SkuModal = (props) => {
    const list = props.modalData.skuList
    const [skuList, setSkuList] = useState([])
    useEffect(() => {
        setSkuList([])
    }, [props.modalVisible])
    const handleCheck = (id, typeId, price) => {
        let _skuList = skuList
        // find type
        let type = list.find(item => item.id === typeId)
        // check exist in skuList
        let index = _skuList.findIndex(item => item.id === id)
        if(index === -1){
            // check max
            let length = _skuList.filter(item => item.typeId === typeId).length
            if(length < type.max){
                _skuList.push({id, typeId, price})
            }
        }else{
            // remove 
            _skuList.splice(index, 1)
        }
        setSkuList([..._skuList])
    }
    const computeChecked = (id) => {
        return skuList.findIndex(item => item.id === id) !== -1
    }
    const computeCount = (typeId) => {
        return skuList.filter(item => item.typeId === typeId).length 
    }
    const computePrice = () => {
        let sum = 0
        skuList.forEach(item => sum += item.price )
        return sum
    }
    const handleAdd = () => {
        if(skuList.length === 0){
            alert('请选择规格')
            return 
        }
        props.handleSkuAdd({id: props.modalData.id, price: props.modalData.price}, skuList)
    }
    return (
        <Modal
            animationType="slide"
            transparent={true}
            visible={props.modalVisible}
            onRequestClose={() => {
                Alert.alert("Modal has been closed.");
            }}
        >
            <View style={styles.centeredView}>
                <View style={styles.modalView}>
                    <Text style={styles.title}>{props.modalData.name}</Text>
                    <SectionList
                        style={styles.sectionList}
                        sections={list}
                        keyExtractor={(item, index) => item + index}
                        renderItem={({ item, section }) => <Item checked={computeChecked(item.id)} typeId={section.id} item={item} handleCheck={handleCheck} />}
                        renderSectionHeader={({ section: { name, max, id } }) => <SkuType count={computeCount(id)} name={name} max={max} />}
                    />
                    <View style={styles.operationContainer}>
                        <Text style={styles.sumPrice}>${computePrice()}</Text>
                        <TouchableOpacity onPress={handleAdd}>
                            <View style={styles.addButton}><Text style={styles.addText}>加入购物车</Text></View>
                        </TouchableOpacity>
                    </View>
                </View>

                <TouchableOpacity onPress={() => props.toggleModal(false, [])}>
                    <Image style={styles.closeIcon} source={require('../assets/close.png')} />
                </TouchableOpacity>
            </View>
        </Modal>
    );
};
export default SkuModal

const styles = StyleSheet.create({
    itemName: {
        marginLeft: 10
    },
    itemLeft: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    itemContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        padding: 15
    },
    checkIcon: {
        width: 25,
        height: 25,
    },
    addButton: {
        backgroundColor: '#76a34e',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 15,
        height: 30,
        width: 100,
    },
    addText: {
        color: '#fff'
    },
    sumPrice: {
        color: '#ff0000',
        fontWeight: 'bold'
    },
    operationContainer: {
        backgroundColor: '#fff',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: 15,
        borderTopWidth: 1,
        borderTopColor: '#f2f2f2' 
    },
    centeredView: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: 'rgba(0, 0, 0, 0.4)'
    },
    sectionList: {
        maxHeight: 400,
    },
    modalView: {
        width: '80%',
        margin: 20,
        backgroundColor: "white",
        borderRadius: 5,
        shadowColor: "#000",
        shadowOffset: {
            width: 0,
            height: 2
        },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5
    },
    title: {
        padding: 10,
        fontSize: 20
    },
    openButton: {
        backgroundColor: "#F194FF",
        borderRadius: 20,
        padding: 10,
        elevation: 2
    },
    textStyle: {
        color: "white",
        fontWeight: "bold",
        textAlign: "center"
    },
    headerContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        backgroundColor: '#ebebeb',
        padding: 10,
    },
    headerText: {},
    headerLimit: {
        color: '#92b67f',
    },
    closeIcon: {
        width: 40,
        height: 40,
    },
});